﻿#region Used Namespaces

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using ContactPrinter.Logic;
using ContactPrinter.Logic.Interfaces;
using ContactPrinter.Model.Interfaces;

#endregion

namespace ContactPrinter
{
    public partial class Form1 : Form
    {
        private IContactService googleContactService;
        private List<IContact> contacts;

        public Form1()
        {
            InitializeComponent();
            DevelopmentInit();
        }

        private void DevelopmentInit()
        {
            var commandLineArgs = Environment.GetCommandLineArgs();
            var loginName = commandLineArgs[1];
            if (!string.IsNullOrEmpty(loginName))
                txtUserName.Text = loginName;
            
            var password = commandLineArgs[2];
            if (!string.IsNullOrEmpty(password))
                txtPassword.Text = password;   
        }


        private void loginHandler(object sender, EventArgs e)
        {
            googleContactService = new GoogleContactService(txtUserName.Text, txtPassword.Text);
            var groups = googleContactService.GetGroups();
            if (groups != null)
            {
                cbGroups.DataSource = new List<IGroup>(groups);
                cbGroups.SelectedIndex = 0;
            }
        }

        private void getContactsHandler(object sender, EventArgs e)
        {
            var selectedContactGroup = cbGroups.SelectedValue as string;
            if (!string.IsNullOrEmpty(selectedContactGroup))
            {
                contacts = new List<IContact>(googleContactService.GetAllContactsFromGroup(selectedContactGroup));
                if (contacts != null)
                {
                    contacts.Sort();
                    gridContacts.DataSource = contacts;
                }
            }
        }

        private void printContactsHandler(object sender, EventArgs e)
        {
            if (contacts == null)
                return;

            using (var contactPrinter = new FullContactPrinter())
            {
                contactPrinter.PrintContacts(contacts);
                using (var printPreviewDialog = new PrintPreviewDialog {Document = contactPrinter})
                {
                    printPreviewDialog.ShowDialog();
                }
            }
        }
    }
}
